package com.lxhll.personnel.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lxhll.personnel.entity.Employee;

import java.util.Date;

public class JwtUtil {
    //默认token有效期,一天
    private static final long EXPIRE_TIME=1000*60*24*24;//有效期
    private static final String TOKEN_SECRET="abcd13924417942liangyi";//秘钥

    public static String sign(Employee employee){
        String jwtToken= JWT.create()
                .withClaim("employeeId",employee.getId())
                .withIssuer("liangyi")//签发人
                .withExpiresAt(new Date(System.currentTimeMillis()+EXPIRE_TIME))
                .sign(Algorithm.HMAC256(TOKEN_SECRET));
        //输出jwt
        System.out.println(jwtToken);
        return jwtToken;
    }
    public static Integer verify(String  token) throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("liangyi").build();
        DecodedJWT jwt = verifier.verify(token); // 验证
        Integer eid = jwt.getClaim("employeeId").asInt();
        System.out.println("-------认证通过--------：");
        System.out.println("员工id: " + eid);
        System.out.println("过期时间：      " + jwt.getExpiresAt());
        return eid;
    }
}
